package kr.hkit.password;

import java.util.ArrayList;
import java.util.List;

import kr.hkit.password.adapter.CustomDrawerAdapter;
import kr.hkit.password.dao.InfoDao;
import kr.hkit.password.db.MyDatabaseManager;
import kr.hkit.password.dto.DrawerItem;
import kr.hkit.password.fragment.account.AccountLogin;
import kr.hkit.password.fragment.account.AccountView;
import kr.hkit.password.fragment.dialog.DialogAlarm;
import kr.hkit.password.fragment.dialog.DialogSearch;
import kr.hkit.password.fragment.item.ItemAdd;
import kr.hkit.password.fragment.item.ItemView;
import kr.hkit.password.service.AlarmService;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity {
	private static final String TAG = "PW";
	public static final String[] columns = { "id", "password", "url", "name" };
	private MyDatabaseManager mIdb;
	private ListView mDrawerList;
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private CustomDrawerAdapter adapter;
	private List<DrawerItem> dataList;
	private Fragment fragment;
	private FragmentManager frgManager;
	private Bundle args;
	private InfoDao info;
	private Intent intent;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (KeyEvent.KEYCODE_BACK == keyCode && info.isLogin()) {
			if (info.isMain()) {
				info.setLogin(false);
				getFragmentManager().beginTransaction()
						.replace(R.id.content_frame, new AccountLogin()).commit();
				getActionBar().hide();
			} else {
				getFragmentManager().beginTransaction()
				.replace(R.id.content_frame, new AccountView()).commit();
			}
			return true;
		} else if (KeyEvent.KEYCODE_BACK == keyCode && !info.isLogin() && info.isMain()) {
			getFragmentManager().beginTransaction()
			.replace(R.id.content_frame, new AccountLogin()).commit();
			info.setMain(false);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.content_frame, new AccountLogin()).commit();
			getActionBar().hide();
		} else {
			getActionBar().show();
		}
		
		menuSetting();

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				invalidateOptionsMenu();
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

		

		intent = new Intent(this, AlarmService.class);
		startService(intent);
	}

	private void menuSetting() {
		info = (InfoDao) getApplication();
		dataList = new ArrayList<DrawerItem>();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		mIdb = MyDatabaseManager.getInstance(this);
		Cursor rs = mIdb.select("list", columns, "account=?", new String[]{ info.getAccount() }, null, null, null);

		while (rs.moveToNext()) {
			dataList.add(new DrawerItem(rs.getString(3),
					R.drawable.ic_action_labels));
		}
		adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
				dataList);
		mDrawerList.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void SelectItem(int possition) {

		fragment = new ItemView();
		args = new Bundle();
		args.putString(ItemView.ITEM_NAME, dataList.get(possition)
				.getItemName());
		fragment.setArguments(args);
		frgManager = getFragmentManager();
		frgManager.beginTransaction().replace(R.id.content_frame, fragment)
				.commit();

		mDrawerList.setItemChecked(possition, true);
		mDrawerLayout.closeDrawer(mDrawerList);

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.d(TAG, "onOptionsItemSelected()");
		if (item.getTitle().equals("추가")) {
			getFragmentManager().beginTransaction()
					.replace(R.id.content_frame, new ItemAdd()).commit();
		} else if (item.getTitle().equals("알람")) {
			if (getFragmentManager().findFragmentByTag("dialog") != null) {
				getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("dialog"));
			}
			DialogAlarm dialog =  new DialogAlarm();
			dialog.show(getFragmentManager(), "dialog");
		} else if (item.getTitle().equals("검색")) {
			if (getFragmentManager().findFragmentByTag("dialog") != null) {
				getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("dialog"));
			}
			DialogSearch dialog =  new DialogSearch();
			dialog.show(getFragmentManager(), "dialog");
		}
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			menuSetting();
			return true;
		}
		return false;
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			SelectItem(position);
		}
	}

}
